/* 
 * AndFollowerStat
 * 
 * Copyright (C) 2009  Daniel Czerwonk <d.czerwonk@googlemail.com>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.dan_nrw.android.followerstat.dao.configuration;

import com.google.inject.Inject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import de.dan_nrw.android.followerstat.R;


/**
 * @author Daniel Czerwonk
 *
 */
public final class ConfigDAO implements IConfigDAO {

	private final Context context;
	private SharedPreferences preferences;
	
	public static String TWITTER_USERNAME = "TwitterUserName";

	
	/**
	 * Creates a new instance of ConfigDAO.
	 * @param context
	 */
	@Inject
	ConfigDAO(Context context) {
	    super();
	    
	    this.context = context;
    }

    
	/**
	 * Creates a new instance of ConfigDAO
	 * @param context
	 * @return
	 */
	public static IConfigDAO createInstance(Context context) {
		return new ConfigDAO(context);
	}
	
	/* (non-Javadoc)
     * @see de.dan_nrw.android.followerstat.dao.configuration.IConfigDAO#getUserName()
     */
    @Override
    public String getTwitterUserName() {
    	this.loadPreferencesIfNeeded();
    	
    	return this.preferences.getString(TWITTER_USERNAME, "");
    }

	/* (non-Javadoc)
     * @see de.dan_nrw.android.followerstat.dao.configuration.IConfigDAO#setUserName(java.lang.String)
     */
    @Override
    public void setTwitterUserName(String userName) {
    	this.loadPreferencesIfNeeded();
    	
    	synchronized(this.preferences) {
    		Editor editor = this.preferences.edit();
    		
    		editor.putString(TWITTER_USERNAME, userName);
    		
    		editor.commit();
        }
    }
    
    private void loadPreferencesIfNeeded() {
    	if (this.preferences != null) {
			return;
		}
		
		this.preferences = this.context.getSharedPreferences(this.context.getString(R.string.applicationName), 
				 											 Context.MODE_PRIVATE);
    }
}